package com.tianqi.tools;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

/**
 * 二维码图片生成工具
 * 
 * 
 * @author dx
 *
 */
public class MatrixToImageWriter {
	private static final int BLACK = 0xFF000000;  
    private static final int WHITE = 0xFFFFFFFF;  
    
    private MatrixToImageWriter() {}  
    
      
    public static BufferedImage toBufferedImage(BitMatrix matrix) {  
      int width = matrix.getWidth();  
      int height = matrix.getHeight();  
      BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
      for (int x = 0; x < width; x++) {  
        for (int y = 0; y < height; y++) {  
          image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
        }  
      }  
      return image;  
    }  
    
      
    public static void writeToFile(BitMatrix matrix, String format, File file)  
        throws IOException {  
      BufferedImage image = toBufferedImage(matrix);  
      if (!ImageIO.write(image, format, file)) {  
        throw new IOException("Could not write an image of format " + format + " to " + file);  
      }  
    }  
    
      
    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)  
        throws IOException {  
      BufferedImage image = toBufferedImage(matrix);  
      if (!ImageIO.write(image, format, stream)) {  
        throw new IOException("Could not write an image of format " + format);  
      }  
    } 
    
    /**
     * 给二维码加上文字
     * @param pressText
     * @param qrFile
     * @param fontStyle
     * @param color
     * @param fontSize
     * @throws Exception
     */
    public static void pressText(String pressText,File qrFile,int fontStyle,Color color,int fontSize) throws Exception{
    	Image src = ImageIO.read(qrFile);
    	int imageW = src.getWidth(null);
    	int imageH = src.getHeight(null);
    	BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
    	Graphics g = image.createGraphics();
    	g.drawImage(src, 0, 0, imageW, imageH, null);
    	//设置画笔的颜色
    	g.setColor(color);
    	//设置字体
    	Font font = new Font("黑体", fontStyle, fontSize);
    	FontMetrics metrics = g.getFontMetrics(font);
    	//文字在图片中的坐标 这里设置在中间
    	int startX = (imageW - metrics.stringWidth(pressText)) / 2;
    	int startY = imageH/2-120;
    	g.setFont(font);
    	g.drawString(pressText, startX, startY);
    	
    	g.dispose();
    	FileOutputStream out = new FileOutputStream(qrFile);
    	ImageIO.write(image, "JPEG", out);
    	out.close();
    	System.out.println("image press success");
    }
    
    /**
     * 生成二维码图片
     * @param url	二维码路径url
     * @param textStr  二维码底部加字字符串
     * @param path 图片保存根目录
     * 
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public static String createQrCodeImg(String url, String textStr, String path){
		try{
			if(url==null || url.trim().length()==0) return null;
			//
	        int width = 300;  
	        int height = 300;  
	        //二维码的图片格式  
	        String format = "gif";  
	        Hashtable hints = new Hashtable();  
	        //内容所使用编码  
	        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
	        BitMatrix bitMatrix = new MultiFormatWriter().encode(url,  
	                BarcodeFormat.QR_CODE, width, height, hints);
	        //保存路径
	        String fileName = IdGenerateTool.generateId();
	        String gifUrl = File.separator + "qrcodeimg" + File.separator + fileName + ".png";
	        //生成二维码  
	        File outputFile = new File(path+gifUrl);
	        if(!outputFile.exists()){
				if(!outputFile.getParentFile().exists()){
					outputFile.getParentFile().mkdirs();
				}
				try {
					outputFile.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile); 
	        if(textStr!=null && textStr.trim().length()>0){
	        	pressText( textStr, outputFile, 5, Color.BLACK, 25);
	        }
	        return gifUrl;
		}catch(Exception e){
			e.printStackTrace();
		}
			return null;
	}
}
